package cn.project.lemontree.controller;

import cn.project.lemontree.utils.CodeUtils;
import io.swagger.annotations.Api;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
@RestController
@RequestMapping("/codegain")
@Api(tags = "验证码生成模块")
@CrossOrigin
public class CodeController {

    public static final String KEY_CODE = "KEY_CODE";
    /**
     * 生成验证码图片
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/code")
    public void code(HttpServletRequest request,
                     HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("image/jpeg");
        response.setHeader("Pragma","No-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expire",0);
        try {
            HttpSession session = request.getSession();
            CodeUtils tool = new CodeUtils();
            StringBuffer code = new StringBuffer();
            BufferedImage image = tool.genRandomCodeImage(code);
            session.removeAttribute(KEY_CODE);
            session.setAttribute(KEY_CODE,code.toString());
            ImageIO.write(image,"JPEG",response.getOutputStream());
            SecurityUtils.getSubject().getSession().setAttribute("KEY_CODE",code.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
